package org.jmc.refmanager.web.wicket.page.search;

import org.apache.wicket.MarkupContainer;
import org.apache.wicket.PageParameters;
import org.apache.wicket.authorization.strategies.role.annotations.AuthorizeInstantiation;
import org.apache.wicket.feedback.ComponentFeedbackMessageFilter;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.link.Link;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.repeater.Item;
import org.apache.wicket.markup.repeater.data.DataView;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.jmc.refmanager.domain.dao.QueryParam;
import org.jmc.refmanager.domain.model.OrgUnit;
import org.jmc.refmanager.domain.model.User;
import org.jmc.refmanager.domain.service.UserManager;
import org.jmc.refmanager.security.SecurityHelper;
import org.jmc.refmanager.util.Util;
import org.jmc.refmanager.web.wicket.form.ServiceSearchForm;
import org.jmc.refmanager.web.wicket.markup.html.navigation.paging.CustomPagingNavigator;
import org.jmc.refmanager.web.wicket.page.service.ServiceDeletePage;
import org.jmc.refmanager.web.wicket.page.service.ServiceEditPage;
import org.jmc.refmanager.web.wicket.page.service.ServiceViewPage;
import org.jmc.refmanager.web.wicket.page.template.TemplatePage;
import org.jmc.refmanager.web.wicket.provider.SortableServiceDataProvider;

/**
 */
@AuthorizeInstantiation(value={"ROLE_MODIF", "ROLE_APPROVER"})
public class ServicesListPage extends TemplatePage {
	@SpringBean(name="userManager")
	private UserManager userManager;

	final QueryParam<OrgUnit> queryParams = new QueryParam<OrgUnit>();
	
	/**
	 * 
	 */
	public ServicesListPage() {
		super();
		initComponents(null);
	}

	/**
	 * @param parameters
	 */
	public ServicesListPage(PageParameters parameters) {
		super(parameters);
		initComponents(parameters);
	}

	private void initComponents(final PageParameters parameters) {
		add(new Label("pageTitle", "Recherche de service"));
//		final QueryParam<OrgUnit> queryParams = new QueryParam<OrgUnit>();
		
		final String matricule = SecurityHelper.getAuthentication().getName();
		
		ServiceSearchForm searchForm = new ServiceSearchForm("searchForm") {
			private static final long serialVersionUID = 1L;

			@Override
			protected void onSubmit(PageParameters params) {
		        if (params != null && !params.isEmpty()) {
					String libCourt = params.getString("libCourt");
					String libLong = params.getString("libLong");
					String codePostal = params.getString("codePostal");
					String codeUO = params.getString("codeUO");

			        OrgUnit example = new OrgUnit();
			        if (!Util.isEmptyOrBlank(libCourt)) {
			        	example.setLibCourt("%" + libCourt);
			        }
			        if (!Util.isEmptyOrBlank(libLong)) {
				        example.setLibLong("%" + libLong);
			        }
			        example.setCodePostal(codePostal);
			        example.setCodeUO(codeUO);
			        // TODO A externaliser dans le service
			        example.setSupprime(false);
			        
			        User user = userManager.getByMatricule(matricule);
			        OrgUnit scope = user.getValidationScope();
			        if (scope != null) {
				        String scopePath = scope.getPath();
				        example.setParentPath(scopePath);
			        }
			        
			        queryParams.setCriteriaExample(example);
		        }
			}
		};
		add(searchForm);
		
        final FeedbackPanel feedback = new FeedbackPanel("feedback", 
        		new ComponentFeedbackMessageFilter(searchForm));
        feedback.setOutputMarkupId(true);
        add(feedback);

        SortableServiceDataProvider dp = new SortableServiceDataProvider(queryParams, matricule);
        
        final DataView<OrgUnit> dataView = new DataView<OrgUnit>("services", dp) {
			private static final long serialVersionUID = 1L;

			@Override
		    public boolean isVisible() {
				return this.getItemCount() > 0;
			}

			@Override
			protected void populateItem(Item<OrgUnit> item) {
				final OrgUnit service = item.getModelObject();
				item.add(new Label("codeUO", new PropertyModel<String>(service, "codeUO")));
				
				MarkupContainer viewLink = new Link<Integer>("viewLink", new PropertyModel<Integer>(service, "id")) {
					private static final long serialVersionUID = 1L;

					@Override
					public void onClick() {
						PageParameters params = new PageParameters();
						params.add("id", getDefaultModelObjectAsString());
						
						setResponsePage(ServiceViewPage.class, params);
					}
				}.add(new Label("libCourt", service.getLibCourt()));
				item.add(viewLink);
				
				item.add(new Label("libLong", service.getLibLong()));
				item.add(new Label("codePostal", service.getCodePostal()));
//				item.add(new Label("commune", service.getCommune()));
				
				// Actions
				MarkupContainer actions = new MarkupContainer("actions") {
					private static final long serialVersionUID = 1L;
				};
				item.add(actions);
				
				boolean serviceChangeInProgress = (service.getChanges() != null && service.getChanges().size() != 0);
				boolean isDirectionValidation = Util.getBlankIfNull(service.getType()).equalsIgnoreCase("C02");
				
				Link<Integer> editLink = new Link<Integer>("editLink", new PropertyModel<Integer>(service, "id")) {
					private static final long serialVersionUID = 1L;

					@Override
					public void onClick() {
						PageParameters params = new PageParameters();
						params.add("id", getDefaultModelObjectAsString());
						
						setResponsePage(ServiceEditPage.class, params);
					}
				};
				editLink.setVisible(!serviceChangeInProgress);
				actions.add(editLink);

				Link<Integer> deleteLink = new Link<Integer>("deleteLink", new PropertyModel<Integer>(service, "id")) {
					private static final long serialVersionUID = 1L;

					@Override
					public void onClick() {
						PageParameters params = new PageParameters();
						params.add("id", getDefaultModelObjectAsString());
						
						setResponsePage(ServiceDeletePage.class, params);
					}
				};
				deleteLink.setVisible(!(serviceChangeInProgress || isDirectionValidation));
				actions.add(deleteLink);

//				Image changeInProgressImg = new Image("changeInProgressImg", new ContextRelativeResource("style"));
//				changeInProgressImg.setVisible(serviceChangeInProgress);
//				actions.add(changeInProgressImg);
				MarkupContainer changeInProgress = new MarkupContainer("changeInProgress") {
					private static final long serialVersionUID = 1L;
				};
				changeInProgress.setVisible(serviceChangeInProgress);
				actions.add(changeInProgress);
			}
		};
		dataView.setItemsPerPage(25);
        add(dataView);

        final Label noResultLabel = new Label("noResult", "Aucun résultat ne correspond à votre recherche");
        noResultLabel.setVisible(dataView.getItemCount()==0);
        add(noResultLabel);

		add(new CustomPagingNavigator("navigator", dataView) {
			private static final long serialVersionUID = 1L;

			@Override
		    public boolean isVisible() {
				noResultLabel.setVisible(dataView.getItemCount()==0);
		        return dataView.getItemCount() > 0;
		    }
		});

	}
}

